import React, {useEffect, useReducer} from 'react';
import {BookOutlined, CloseCircleOutlined, SettingOutlined, UserOutlined} from "@ant-design/icons";
import {logoutApi} from "@/api/auth/login.js";
import {AuthUtil} from "@/utils/auth.js";
import {Button, Dropdown, message, Modal} from "antd";
import {defaultStore} from "@/store/default-store.js";
import {GlobalConfigView} from "@/views/index.js";
import {router} from "@/routes/index.jsx";
import {useRouter} from "@/hooks/index.js";
import {useStore} from "@/store/index.js";

const items = [
  {
    key: '1',
    label: "用户信息",
    icon: <BookOutlined/>
  },
  {
    key: '2',
    label: "全局设置",
    icon: <SettingOutlined/>
  },
  {
    type: 'divider',
  },
  {
    key: '3',
    label: "退出当前登录",
    icon: <CloseCircleOutlined/>,
    danger: true
  },
];

const menuStatus = {
  isOpen: false,
  confirmLoading: false
}
const menuReducer = (state, action) => {
  switch (action.type) {
    case 'TOGGLE_CLOSE':
      return {
        ...state,
        isOpen: !state.isOpen
      }
    case 'TOGGLE_OK':
      return {
        ...state,
        confirmLoading: true,
      }
    case 'LOADING_SUCCESS':
      return {
        ...state,
        confirmLoading: false,
        isOpen: !state.isOpen
      }
  }
}

const UserProfileComp = () => {
  const [menuState, menuDispatch] = useReducer(menuReducer, menuStatus)
  const router = useRouter()
  const {layoutSettings} = useStore().defaultStore

  useEffect(() => {
    async function temp() {
      if (menuState.confirmLoading) {
        await logoutApi().then(e => {
          menuDispatch({type: 'LOADING_SUCCESS'});
          AuthUtil.removeToken()
          message.info("您已退出账户，请重新登陆！", 1.5)
          router.replace("/login")
        }).catch(err => {
          message.error("退出登录失败！", 1.5)
          menuDispatch({type: 'LOADING_SUCCESS'});
        })
      }
    }

    temp()
  }, [menuState.confirmLoading, router])

  const onMenuClick = ({key}) => {
    switch (key) {
      case '1':
        router.push("/dashboard/account")
        break;
      case '2':
        defaultStore.changeDrawer()
        console.log(layoutSettings.configViewOpen)
        break;
      case '3':
        menuDispatch({type: "TOGGLE_CLOSE"})
        break;
      default:
        break;
    }
  };

  return (
    <>
      <Dropdown
        menu={{
          items,
          onClick: (key) => onMenuClick(key)
        }}
        placement="bottomLeft"
      >
        <Button type='text' icon={<UserOutlined/>} onClick={(e) => e.preventDefault()}/>
      </Dropdown>

      <Modal
        title="退出账号"
        open={menuState.isOpen}
        onOk={() => menuDispatch({type: "TOGGLE_OK"})}
        confirmLoading={menuState.confirmLoading}
        onCancel={() => menuDispatch({type: "TOGGLE_CLOSE"})}
      >
        <p>您确定要退出当前账号吗？</p>
      </Modal>

      <GlobalConfigView/>
    </>
  );
};

export default UserProfileComp;
